<template>
  <view>
    <cu-custom bgColor="bg-gradual-pink" :isBack="false">
      <block slot="backText">返回</block>
      <block slot="content">外协送货</block>
      <block slot="right">
        <uni-icons type="home" size="20" color="white" class="home-icon" @click="goHome"></uni-icons>
      </block>
    </cu-custom>
	<view><text>分享ID:{{uuid?uuid.split('-')[0]:""}}</text></view>
    <view class="order-page">
      <view class="order-list">
        <view
          class="order-item"
          v-for="(order, index) in orders"
          :key="order.id"
          @click="toggleOrder(index,order)"
        >
          <view class="order-header">
            <text class="order-id">订单号: {{ order.outsourceNo }}</text>
            <text class="order-date">{{ order.orderDate }}</text>
            <text class="order-status">{{ order.status_dictText }}</text>
            <!-- 添加拍照上传按钮 -->
            <uni-icons type="camera-filled" size="24" @click="chooseImage(index)" />
          </view>
          <view v-if="expandedOrders.includes(index)" class="order-details">
            <view
              class="detail-item"
              v-for="(detail,k) in order.details"
              :key="detail.id"
            >
			  <text class="detail-name">{{ k }}</text>
              <text class="detail-name">{{ detail.productName }}</text>
			  <text class="detail-name">{{ detail.processName }}</text>
              <text class="detail-price">{{ detail.unitPrice }}</text>
              <text class="detail-quantity">{{ detail.qty }}</text>
				<text class="detail-quantity">{{ detail.area }}</text>
				<text class="detail-quantity">{{ detail.areaUnitName }}</text>
				<text class="detail-quantity">{{ detail.weight }}</text>
				<text class="detail-quantity">{{ detail.weightUnitName }}</text>
            </view>
            <!-- 显示图片缩略图 -->
            <view class="image-preview" v-if="order.images && order.images.length > 0">
              <image
                v-for="(image, imgIndex) in order.images"
                :key="imgIndex"
                :src="getImage(image)"
                mode="aspectFill"
                @click="previewImage(order.images, imgIndex)"
                style="width: 80rpx; height: 80rpx; margin-right: 10rpx;"
              />
			  <view class="cu-tag bg-red radius" @tap.stop="DelImg($event,order.images,index)" :data-index="index">
			  	<text class='cuIcon-close'></text>
			  </view>
            </view>
          </view>
        </view>
      </view>
    </view>
	    <!-- 添加提交按钮 -->
	    <button class="submit-button" @click="submitData">提交</button>
  </view>
</template>

<script>
import { ACCESS_TOKEN,USER_NAME,USER_INFO,SASS_TENANT_ID,EMPLOYEE_INFO,SASS_DOMAIN_ID,SASS_DOMAIN_NAME} from "@/common/util/constants"
import configService from '@/common/service/config.service.js';
import { forEach } from "../../common/luch-request/utils";
	import api from '@/api/api.js'
	
export default {
  data() {
    return {
      orders: [
        {
          id: '1001',
          date: '2023-10-01',
          status: '已完成',
          details: [
            { id: '1', name: '商品A', price: 100, quantity: 2 },
            { id: '2', name: '商品B', price: 200, quantity: 1 }
          ],
          images: [] // 存储该订单的图片
        },
        {
          id: '1002',
          date: '2023-10-02',
          status: '待发货',
          details: [
            { id: '3', name: '商品C', price: 150, quantity: 3 },
            { id: '4', name: '商品D', price: 300, quantity: 1 }
          ],
          images: []
        }
      ],
      expandedOrders: [], // 存储当前展开的订单索引
	  loading:false,
	   uuid : null, //'ebfd5729-7f9e-4109-a025-077c17a9edcc',
	   tenantId : null, //'22',
	   supplierId : null, // "1820383131371315202",
	   loginRes : null,
	   err:null,
	   checkString:null,
	   // imageObject:{},
	  url: {
		  uploadUrl:"/sys/common/upload",
		       list: '/opm/opmOutsourceProcess/list',
		  queryById: '/opm/opmOutsourceProcess/queryOpmOutsourceProcessItemByMainId',
		      login: '/sys/shareLinkLogin',
		  checkSign: '/sys/checkUuid',
		  editAttachment: '/opm/opmOutsourceProcess/editAttachment',
	  },
    };
  },
    onLoad(options) {
  	// 处理获取到的分享参数
  	setTimeout(() => {
  	  console.log(options);
  	  if (options.uuid) {
  		this.uuid =options.uuid;
  	  } 
  	  if (options.supplierId) {
  		this.supplierId = options.supplierId;
  	  } 
  	  if (options.tenantId) {
  		this.tenantId = options.tenantId;
  	  }	
	  if (this.uuid) {
		  this.checkSign()
	  }
  	}, 800);
    },
  created() {	
  },
  mounted(){	
  },
  methods: {	  
	  checkSign() {
		  let that = this
		this.loading = true;
		let params = {uuid:this.uuid + this.tenantId}
		this.$http.get(this.url.checkSign, {
				params: params
		}).then((res) => {
			that.checkString = JSON.stringify(res)
			if (res.data.success) {
				const result = res.data.result
				uni.setStorageSync(SASS_TENANT_ID,result.tenantId);
				this.biz = 'temp/' + result.tenantId  
				this.login()
			} else {
				this.$tip.toast(res.data.message)
			}
		}).catch(err => {
					that.err = JSON.stringify(err)
					that.$tip.error(err.data.message)
				}).finally(() => {
			that.loading = false
		})
	  },
	  login(){
		  let that = this
			this.loading = true;
			this.$http.post(this.url.login, {
					uuid: this.uuid,
					supplierId: this.supplierId,
					tenantId: this.tenantId,
			}).then((res) => {
				console.log(res)
				that.loginRes = JSON.stringify(res)
						if (res.data.success) {					
							const result = res.data.result
							const userInfo = result.userInfo
							uni.setStorageSync(ACCESS_TOKEN,result.token);
							uni.setStorageSync(USER_INFO,userInfo);
							this.loadData()
						} else {
							this.$tip.toast(res.data.message)
						}
				}).catch(err => {
					that.err = JSON.stringify(err)
					that.$tip.error(err.data.message)
				}).finally(() => {
					that.loading = false
				})
	  },	  
	  loadData(pageCurrent) {
	  		let that = this
	  		if (!this.url.list) {
	  			this.$tip.alert("请设置url.list属性!")
	  			return
	  		}
			let params = {
	  				pageNo: 1,
	  				pageSize: 100,
	  				column: 'createTime,updateTime',
	  				order: 'desc',
	  			}
			let superArr = []
			superArr.push({"rule":"eq","type":"string","val":'3',"field":"op.status"})
			superArr.push({"rule":"eq","type":"string","val":this.supplierId,"field":"op.supplierId"})
			params.superQueryMatchType = 'and'
			params.superQueryParams = encodeURIComponent(JSON.stringify(superArr))
			
	  		this.loading = true;
	  		this.$http.get(this.url.list, {
	  			params: params
	  		}).then((res) => {
	  			if (res.data.success) {
	  				that.orders = res.data.result.records || res.data.result;
					that.orders.forEach((item,index)=>{
						if (item.attachment) {
							item.images = item.attachment.split(',')
							// that.imageObject[index] = JSON.parse(JSON.stringify(item.images))  
						}						
					})
					that.orders.details = []
					// that.orders.images = []
	  			} else {
	  				this.$tip.alert(res.message)
	  			}
	  	 }).finally(() => {
	  			that.loading = false
	  		})
	  	},

    goHome() {
      uni.navigateTo({
        url: '/pages/index/index'
      });
    },
    toggleOrder(index,order) {
		let id = order.id
		let params = {'id':id}			
		this.loading = true
		this.$http.get(this.url.queryById, {
			params: params
		}).then(res => {
			this.loading = false
			order.details = res.data.result.records || res.data.result;
			// order.images = []
			const idx = this.expandedOrders.indexOf(index);
			if (idx > -1) {
			  this.expandedOrders.splice(idx, 1); // 如果已经展开，则关闭
			} else {
			  this.expandedOrders.push(index); // 如果未展开，则展开
			}
		})
    },
    // 选择图片并上传
    chooseImage(index) {
		let that = this
		      // 确保当前订单详情项是展开的
		      // if (!this.expandedOrders.includes(index)) {
		      //   this.expandedOrders.push(index);
		      // }
	  // if (!this.imageObject[index]) {
		 //  this.imageObject[index] = []
	  // }
	   
      uni.chooseImage({
        count: 1, // 一次只允许选择一张图片
        sourceType: ['camera'], // 只允许拍照
		
        success: (res) => {
			that.$http.upload(that.$config.apiUrl+that.url.uploadUrl + "?biz=" + this.biz, {
					filePath: res.tempFilePaths[0],
					name: 'file'
				})
				.then(result => {
					if (!that.orders[index].images) {
						
									// 使用 Vue.set 确保 Vue 能检测到数组的创建
					  that.$set(that.orders[index], 'images', []);
					}
					// 使用 Vue.set 确保 Vue 能检测到数组的更新
					that.$set(that.orders[index].images, that.orders[index].images.length, result.data.message); 
					   // that.imageObject[index].push(result.data.message)
					if (!this.expandedOrders.includes(index)) {
						this.expandedOrders.push(index);
					}
				})
				.catch(err => {
					that.$tip.error(err.data.message)
				});

			// that.$http.upload(that.$config.apiUrl + that.uploadUrl + "?biz=" + this.biz, {
			// 		filePath: res.tempFilePaths[0],
			// 		name: 'file',
			// 	})
			// 	.then(res => {
			// 		// that.baseFormData.avatar=res.data.message;
			// 		that.uploadImgList.push(res.data.message)
			// 		that.imgList.push(configService.staticDomainURL + "/" + res.data.message)
			// 	})
			// 	.catch(err => {
			// 		that.$tip.error(err.data.message)
			// 	});
			

        },
        fail: (err) => {
          console.error('选择图片失败', err);
        }
      });
    },
	DelImg(e,images,index) {
		uni.showModal({
			title: '删除',
			content: '确定要删除图片吗？',
			cancelText: '取消',
			confirmText: '确定',
			success: res => {
				debugger
				if (res.confirm) {
					// 删除图片
					const imgIndex = e.currentTarget.dataset.index;
					this.orders[index].images.splice(imgIndex, 1);
					// 使用 Vue.set 更新数组，让 Vue 能检测到变化
					this.$set(this.orders, index, {...this.orders[index] });
				}
			}
		})
	},
	getImage(image) {
		return api.getFileAccessHttpUrl(image)
	},
    // 预览图片
    previewImage(images, currentIndex) {
		let _images = []
		images.forEach((v)=>{
			_images.push( api.getFileAccessHttpUrl(v)	)
		})
      uni.previewImage({
        urls: _images,
        current: _images[currentIndex]
      });
    },
	    // 添加提交数据方法
	    submitData() {
			debugger
					this.$tip.loading();
					this.orders.forEach((item,index)=>{
						if (item.images) {
							item.attachment = item.images.join()
						}						
					})
					
					let opmOutsourceProcessVo = {}
					opmOutsourceProcessVo.opmOutsourceProcessList = this.orders
					let params = JSON.stringify(opmOutsourceProcessVo)
					this.$http.post(this.url.editAttachment,params).then(res=>{
						console.log(res)
						this.$tip.loaded();
						if (res.data.success){
							this.$tip.toast('提交成功')
							this.$Router.replace({name:'index'})
						}					
					}).catch(()=>{
						this.$tip.loaded();
						this.$tip.error('提交失败')
					});
	    }
  }
};
</script>

<style scoped lang="scss">
  // 添加图标的样式
  .home-icon {
    // position: absolute;
    // top: 20rpx;
    margin-left: 10px;
  }

  .order-page {
    padding: 20rpx;
  }

  .order-list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
  }

  .order-item {
    background-color: #ffffff;
    border-radius: 10rpx;
    box-shadow: 0px 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }

  .order-header {
    height: 60px;
    padding: 16rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx solid #eeeeee;
  }

  .order-header > text {
    font-size: 28rpx;
    color: #333333;
  }

  .order-header > .order-id {
    font-weight: bold;
  }

  .order-header > .order-date,
  .order-header > .order-status {
    color: #666666;
  }

  .detail-item {
    padding: 8rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #ffffff;
    border-radius: 10rpx;
    box-shadow: 0px 4rpx 12rpx rgba(0, 0, 0, 0.1);
    margin-bottom: 10rpx;
	    // 允许换行
	    flex-wrap: wrap; 
  }

  .detail-item:last-child {
    margin-bottom: 0;
  }

  .detail-item > text {
    font-size: 26rpx;
    color: #333333;
	    // 为每个字段设置最小宽度
	    min-width: 80rpx; 
	    margin-right: 10rpx;
	    // 超出部分省略显示
	    overflow: hidden;
	    text-overflow: ellipsis;
	    white-space: nowrap;
  }

  .detail-item > .detail-name {
    flex: 1;
    margin-right: 16rpx;
  }

  .detail-item > .detail-price,
  .detail-item > .detail-quantity {
    color: #666666;
  }

  .image-preview {
    display: flex;
    flex-wrap: wrap;
    margin-top: 10rpx;
  }
  
  // 添加提交按钮样式
  .submit-button {
    position: fixed;
    left: 20rpx;
    bottom: 20rpx;
    // 修改为蓝色透明背景
    background-color: rgba(0, 123, 255, 0.5); 
    color: white;
    border: none;
    border-radius: 10rpx;
    padding: 10rpx 20rpx;
    font-size: 28rpx;
  }
</style>